package cn.cvs.web.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class AuthorizationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getSession().getAttribute("currUser") == null){ //判断session中是否有登录用户
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            System.out.println("请先登录!(Filter控制)");
            out.print("<script>alert('请先登录!(Interceptor控制)');" +
                    "location.href='"+request.getContextPath()+"/login.html"+"'</script>");

            return false ;//sesion没有用户,返回false 请求不通过

        }else{

            return true; //请求通过
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //请求执行之前执行的代码,前提是 preHandle 返回 true
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求结束执行的代码 ,前提是 preHandle 返回 true
    }
}
